<template>
  <div class="app-container">
    <van-nav-bar :title="fieldData.name" left-arrow @click-left="$router.back()" />
    <div class="content-box">
      <van-tabs v-model="tabActive">
        <van-tab title="订场">
          <div class="card booking">
            <div class="date-select-box">
              <el-scrollbar>
                <div class="date-item" v-for="date in dateList" :class="checkedDate == date && 'active'"
                  @click="checkDate(date)">
                  <div class="week">{{ getWeek(date) }}</div>
                  <div class="date">{{ date }}</div>
                </div>
              </el-scrollbar>
            </div>
            <div class="booking-table">
              <div class="column time">
                <div class="header">-</div>
                <div class="time-item" v-for="(time, index) in timeList" :key="index">{{ time }}</div>
              </div>
              <div class="column place" v-for="(place, index) in fieldOptionList" :key="index">
                <div class="header">{{ place.fieldName }}</div>
                <div class="place-item" v-for="(time, time_index) in place.timeList" :key="time_index"
                  :class="{ active: placeItemIsActive(place, time), record: placeItemIsRecord(place, time, 'record'), my: placeItemIsRecord(place, time, 'my') }"
                  @click="checkPlace(place, time)">
                  <svg-icon icon-class="check" v-if="placeItemIsActive(place, time)" />
                  <svg-icon icon-class="check-calendar" v-else-if="placeItemIsRecord(place, time, 'my')" />
                  <span class="record" v-else-if="placeItemIsRecord(place, time, 'record')">已订</span>
                  <span class="empty" v-else="">&nbsp</span>
                </div>
              </div>
            </div>
            <div class="handle-box">
              <div class="place-num">已选:{{ checkedOptionList.length }}</div>
              <div class="submit-btn" @click="submit">提交预定</div>
            </div>
          </div>
        </van-tab>
        <van-tab title="场地介绍">
          <div class="card">
            <img class="cover" :src="fieldData.imageUrl" alt="">
            <div class="tip">
              <span class="label">类型：</span>{{ fieldData.type }}
            </div>
            <div class="tip">
              <span class="label">开放时间：</span>{{ fieldData.openTimePeriod }}
            </div>
            <div class="tip">
              <span class="label">地址：</span>{{ fieldData.description }}
            </div>
            <div class="tip">
              {{ fieldData.type }}
            </div>
          </div>
        </van-tab>
        <van-tab title="场地布局">
          <div class="card">
            <img class="cover" :src="fieldData.layoutImageUrl" alt="">
            <div class="tip">
              <span class="label">场地面积：</span>{{ fieldData.area }}M²
            </div>
            <div class="tip">
              <span class="label">容纳人数：</span>{{ fieldData.capacity }}M²
            </div>
          </div>
        </van-tab>
      </van-tabs>
    </div>
  </div>
</template>

<script>
import dayjs from 'dayjs';
dayjs.locale('zh-cn');
// dayjs().locale('zh-cn').format()
import * as api from '@/api/bookingManger/index.js';
import { mapGetters } from 'vuex';

export default {
  name: 'BookingDetail',
  data() {
    return {
      fieldId: null,
      fieldData: {},
      tabActive: '',
      bookTimePeriod: null,
      dateList: [],
      checkedDate: '',
      timeList: [],
      fieldOptionList: [],
      checkedOptionList: [],
      recordList: [],
      num: 14,
    };
  },
  computed: {
    ...mapGetters(['userId']),
  },
  created() {
    if (this.$route?.query?.id) this.fieldId = this.$route.query.id;
    if (this.$route?.query?.bookTimePeriod) this.bookTimePeriod = this.$route.query.bookTimePeriod;
    this.getData();
    // 日期列表
    for (let index = 0; index < 6; index++) {
      this.dateList.push(dayjs().add(index, 'day').format('YYYY-MM-DD'));
    }
    if (this.bookTimePeriod) {
      const bookTimePeriodDate = dayjs(this.bookTimePeriod).format('YYYY-MM-DD');
      if (this.dateList.find((date) => date == bookTimePeriodDate)) {
        this.checkedDate = bookTimePeriodDate;
      } else {
        this.dateList = [];
        for (let index = 0; index < 6; index++) {
          this.dateList.push(dayjs(bookTimePeriodDate).add(index, 'day').format('YYYY-MM-DD'));
        }
        this.checkedDate = this.dateList[0];
      }
    } else this.checkedDate = this.dateList[0];
  },
  methods: {
    // 获取数据
    async getData() {
      this.dataLoading = true;
      // 获取场地信息
      const { data } = await api.getBookFieldInfo(this.fieldId);
      this.fieldData = data;
      this.timeList = this.getTimeArray(this.fieldData);
      // 获取场地选项信息
      const { rows: optionRows } = await api.getBookOptionList({ fieldId: this.fieldId, pageSize: 1000 });
      this.fieldOptionList = optionRows;
      this.fieldOptionList.forEach((item) => {
        item.timeList = this.getTimeArray(this.fieldData);
      });
      // 获取场地选项记录
      const { rows: recordRows } = await api.getBookRecordList({ fieldId: this.fieldId, pageSize: 1000 });
      this.recordList = recordRows;
    },
    // 生成时间列表
    getTimeArray({ openTimePeriod, minBookingUnit }) {
      const startTime = dayjs(dayjs().format(`YYYY-MM-DD ${openTimePeriod.split('-')[0]}`)); // 设置起始时间
      const endTime = dayjs(dayjs().format(`YYYY-MM-DD ${openTimePeriod.split('-')[1]}`)); // 设置结束时间
      const diffMinute = endTime.diff(startTime, 'minute'); // 时间差
      const itemNum = diffMinute / minBookingUnit; // 时间选项个数
      // 生成时间列表
      const timeList = [];
      for (let i = 0; i <= itemNum; i++) {
        const time = startTime.add(minBookingUnit * i, 'minute').format('HH:mm');
        timeList.push(time);
      }
      return timeList;
    },
    // 显示星期
    getWeek(date) {
      if (dayjs().format('YYYY-MM-DD') == date) return '今天';
      const d = dayjs(date).format('d');
      const week = ['日', '一', '二', '三', '四', '五', '六'];
      return `周${week[d]}`;
    },
    // 选择日期
    checkDate(date) {
      this.checkedDate = date;
      this.checkedOptionList = [];
    },
    // 选择场地
    checkPlace(place, time) {
      // 判断是否已经选择
      const hasPlaceItem = this.placeItemIsActive(place, time);
      if (hasPlaceItem) {
        // 过滤已选项，取消选中
        this.checkedOptionList = this.checkedOptionList.filter((item) => {
          const isHasPlaceItem = hasPlaceItem.optionId == item.optionId && hasPlaceItem.time == item.time;
          return !isHasPlaceItem;
        });
      } else {
        // 判断是否超过最大数量
        if (this.checkedOptionList.length >= this.fieldData.maxNum) {
          this.$message.warning({
            message: `当前最多只能预订 ${this.fieldData.maxNum} 个场次`,
          });
        } else {
          this.checkedOptionList.push({ optionId: place.id, fieldName: place.fieldName, time });
        }
      }
    },
    // 场地是否选中
    placeItemIsActive(place, time) {
      const res = this.checkedOptionList.find((item) => {
        return item.optionId == place.id && item.time == time;
      });
      return res;
    },
    // 场地是否记录选中
    placeItemIsRecord(place, time, type) {
      const res = this.recordList.find((item) => {
        const isRecord = item.optionId == place.id && item.bookTimePeriod == `${this.checkedDate} ${time}`;
        const isMy = item.userId == this.userId;
        if (type == 'record') return isRecord;
        if (type == 'my') return isRecord && isMy;
      });
      return res;
    },
    // 提交预订
    async submit() {
      if (!this.checkedOptionList.length) return this.$message({ message: '请选择场地', type: 'warning' });
      await this.checkedOptionList.reduce(async (pre, item) => {
        await pre;
        await api.addBookRecord({
          fieldId: this.fieldId,
          optionId: item.optionId,
          bookTimePeriod: `${this.checkedDate} ${item.time}`,
          userId: this.userId,
        });
      }, Promise.resolve());
      this.$message({ message: '预订成功', type: 'success' });
      this.$router.go(0);
    },
  },
};
</script>

<style lang="scss" scoped>
.content-box {
  width: calc(100% - 30px);
  height: calc(100% - 70px);
  padding: 10px 15px;
  display: flex;
  flex-direction: column;
}

::v-deep .van-tabs {
  height: 100%;

  .van-tabs__nav {
    background-color: transparent;

    .van-tab {
      font-size: 16px;
      color: #b7b7b7;

      &.van-tab--active {
        color: #323233;
      }
    }

    .van-tabs__line {
      background-color: #165dff;
    }
  }

  .van-tabs__content {
    margin-top: 15px;
    height: calc(100% - 60px);

    .van-tab__pane {
      height: 100%;
    }
  }
}

.card {
  border-radius: 10px;
  padding: 15px;
  background-color: #fff;
  width: calc(100% - 30px);
  height: calc(100% - 30px);

  // margin-bottom: 15px;
  &.booking {
    display: flex;
    flex-direction: column;
  }

  .cover {
    width: 100%;
    margin-bottom: 10px;
  }

  .tip {
    color: #8d8d8d;
    font-size: 15px;
    white-space: pre-wrap;
    margin-bottom: 10px;

    &:last-child {
      margin-bottom: 0px;
    }

    &.description {
      font-size: 15px;
    }

    .label {
      display: inline-block;
      width: 75px;
    }
  }
}

.date-select-box {
  // display: flex;
  flex-shrink: 0;
  width: 100%;
  margin-bottom: 10px;
  white-space: nowrap;
  overflow: auto;

  .date-item {
    display: inline-block;
    padding: 12px;
    border-radius: 8px;
    background: #e9e9e9;
    text-align: center;
    margin-right: 10px;

    &:last-child {
      margin-right: 0px;
    }

    &.active {
      background-color: #8fb1ff4c;
      color: #165dff;
    }
  }
}

.booking-table {
  flex: 1;
  width: 100%;
  white-space: nowrap;
  overflow: auto;
  display: flex;

  .column {
    display: inline-block;
    text-align: center;
    padding: 0 5px;

    .header {
      padding: 10px;
    }

    .time-item,
    .place-item {
      margin: 0 auto;
      margin-bottom: 10px;

      &:last-child {
        margin-bottom: 0px;
      }

      width: 80px;
      height: 50px;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .time-item {
      width: 45px;
      border: 1px solid transparent;
    }

    .place-item {
      // padding: 15px;
      background: #ebebeb;
      border: 1px solid #ebebeb;

      &.active {
        border: 1px solid #165dff4c;
        background-color: #8fb1ff4c;
        color: #165dff;
      }

      &.record {
        border: 1px solid #909399;
        background-color: #909399;
        pointer-events: none;
        color: #eee;
      }

      &.my {
        border: 1px solid #165dff4c;
        background-color: #165dff;
        color: #fff;
      }

      .svg-icon {
        font-size: 20px;

        &.check-calendar {
          font-size: 26px;
        }
      }
    }
  }
}

.handle-box {
  margin-top: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .place-num {
    color: #165dff;
  }

  .submit-btn {
    padding: 7px 30px;
    border-radius: 20px;
    background-color: #165dff;
    color: #fff;
    cursor: pointer;
  }
}
</style>
